﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace Daun.Cores.Entities
{
    [TypeConverter(typeof(DocumentPropertyConverter))]
    public class DocumentProperty
    {
        private readonly Dictionary<string, string> values = new Dictionary<string, string>();
        private readonly Dictionary<string, string> types = new Dictionary<string, string>();
        public string this[string key]
        {
            get
            {
                string value;
                values.TryGetValue(key, out value);

                return value;
            }
            set
            {
                // validate input
                try
                {
                    MongoDB.Bson.BsonValue val = MongoHelpers.GetBsonValue(types[key], value);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message, "Input Validation");
                    return; 
                }
                if (value == null) values.Remove(key);
                else
                    values[key] = value;
            }
        }
        public string DocumentCategory { set; get; }        

        public string[] GetKeys()
        {
            List<string> keys = new List<string>();
            foreach (var key in values.Keys)
            {
                if (key == "_id")
                    continue;
                keys.Add(key);
            }
            return keys.ToArray();
        }
        public void Add(string key, string value,string type)
        {
            values[key] = value;
            types[key] = type;
        }
        public void Add(List<Document> items)
        {
            foreach (var item in items)
            {
                values[item.Key] = item.Value;
                types[item.Key] = item.DocumentType;
            }
        }
        public Dictionary<string, string> GetKeysValues()
        {
            Dictionary<string, string> list = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> item in values)
            {
                if (item.Key == "_id" && string.IsNullOrEmpty(item.Value))
                    continue;
                list.Add(item.Key, item.Value);
            }
            return list;
        }

        public List<Document> GetDocuments()
        {
            List<Document> list = new List<Document>();
            foreach (KeyValuePair<string, string> item in values)
            {
                Document doc = new Document(item.Key, item.Value, types[item.Key]);
                list.Add(doc);
            }
            return list;
        }

    }
}
